package org.example.demo33.controller;

import com.alibaba.fastjson.JSON;
import org.example.bean.SocketMessage;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

//@Slf4j
@ServerEndpoint("/webSocket/{uid}")
@Component
public class OneToAnOtherOneWebSocket {
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    private static ConcurrentHashMap<String, Session> clients = new ConcurrentHashMap<>();


    @OnOpen
    public void onOpen(Session session) {
        onlineCount.incrementAndGet();
        clients.put(session.getId(), session);
        System.out.println();
        System.out.println("== 有新连接加入 id =  " + session.getId() + " , 当前在线人数为: " + onlineCount.get());
        sendMessage(session, "欢迎你的加入");
    }

    @OnClose
    public void onClose(Session session) {
        onlineCount.decrementAndGet();
        clients.remove(session.getId());
        System.out.println("== 有一为连接关闭 id =  " + session.getId() + " , 当前在线人数为: " + onlineCount.get());
    }

    @OnMessage
    public void onMessage(Session session, String message) {
        System.out.println("== 服务端收到 id =  " + session.getId() + " 的客户端 消息：" + message);
        // 这里使用Slf4j log info 会导致 接收不到 message

        try {
            SocketMessage socketMessage = JSON.parseObject(message, SocketMessage.class);
            if (socketMessage == null) {
                System.out.println("== socketMessage 解析 socketMessage 为空");
                return;
            }
            Session toSession = clients.get(socketMessage.uid);
            if (toSession == null) {
                System.out.println("== socketMessage 未查询到此用户 uid : " + socketMessage.uid);
                return;
            }
            sendMessage(toSession, socketMessage.msg);
        } catch (Exception e) {
            System.out.println("== onMessage 解析发生异常，信息 ：{}" + e.toString());
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("== 连接 发生异常 id =  " + session.getId() + " , 异常信息: " + error.toString());
    }

    private void sendMessage(Session toSession, String message) {
        try {
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            System.out.println("== 发送 消息发生异常 : " + e.toString());
        }
    }
}
